export class Event {
    static setDefaultEventBus(EventBus) {
        this.eventBus = EventBus
    }
    constructor({ key, callback, withEventInfo = false }, EventBus) {
        this.eventBus = EventBus || Event.eventBus;
        this.id = Event.ID++;
        this.key = key
        this.callback = callback
        this.withEventInfo = withEventInfo;
        this.on()
    }
    on() {
        const { key, callback } = this;
        this.eventBus.$on(key, callback)
    }
    off() {
        const { key, callback } = this;
        this.eventBus.$off(key, callback)
    }
    destroy() {
        this.off();
        this.eventBus = null;
        this.key = null;
        this.callback = null;
    }

}
Event.ID = 0;


export class EventGroup {
    constructor(EventBus) {
        this.id = EventGroup.ID++;
        this.eventBus = EventBus || EventGroup.eventBus
        this.eventStack = []
    }

    static setDefaultEventBus(EventBus) {
        this.eventBus = EventBus
    }

    on(list) {
        list.forEach(([key, callback, withEventInfo = false]) => {
            this.add([key, callback, withEventInfo])
        })
    }

    emit(key, ...params) {
        this.eventBus.$emit(key, ...params)
    }

    add([key, callback, withEventInfo]) {
        const event = new Event({ key, callback, withEventInfo }, this.eventBus)
        this.eventStack.push(event)
    }

    remove(key) {
        const index = this.eventStack.findIndex(member => member.key === key)
        if (index > 0) {
            const event = this.eventStack[index]
            this.eventStack.splice(index, 1)
            event.destroy()
        }
    }

    off() {
        this.eventStack.forEach(member => {
            member.off()
        })
        this.eventStack = []
    }

    destroy() {
        this.off()
        this.eventBus = null;
    }
}
EventGroup.ID = 0;
